import Driver from "driver.js"
import { useEffect } from "react"
import "./index.less"

export interface RoamingBootProps {
  storageKey: string
  steps: {
    name?: string
    element?: string
    title: string
    description: string
    position?: string
    onNext?: (value: Driver) => void
  }[]
  onDone: () => void
}

export const RoamingBoot = ({
  storageKey,
  steps,
  onDone
}: RoamingBootProps) => {
  const driver = new Driver({
    opacity: 0.7,
    animate: true,
    allowClose: false, // Whether the click on overlay should close or not
    closeBtnText: "跳过",
    doneBtnText: "我知道了",
    nextBtnText: "下一步", // 下一步的按钮文案
    onReset: () => {
      onDone()
      localStorage.setItem(storageKey, "1")
    }
  })
  const startDriver = () => {
    let timer: number
    const mySteps = steps.filter((item) => {
      if (
        (item.element &&
          document.getElementsByClassName(item.element)[0].parentElement
            ?.parentElement?.parentElement) ||
        document.getElementsByName(`code_${item.name}`)[0]
      ) {
        return item
      }
    })
    console.log(mySteps)
    const step = mySteps.map((item, index) => {
      return {
        element: item.element
          ? document.getElementsByClassName(item.element)[0].parentElement
              ?.parentElement?.parentElement
          : document.getElementsByName(`code_${item.name}`)[0],
        popover: {
          title: `<div>${item.title}<div/>`,
          description: `<div>${
            item.description
          }<div class="steps_num"><div style='font-size: 14px'>${index + 1}/${
            mySteps.length
          }</div></div></div>`,
          position: item.position
        },
        onNext: () => {
          item.onNext?.(driver)
        }
      }
    })
    driver.defineSteps(step as Driver.Step[])
    setTimeout(() => {
      driver.start()
    }, 500)

    return () => {
      clearTimeout(timer)
    }
  }

  useEffect(() => {
    if (localStorage.getItem(storageKey) !== "1") {
      startDriver()
    }
  }, [])

  return <></>
}
